package common;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.ParseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import domain.PostBean;

/**
 * 登陆发帖类
 * 
 * @author Administrator
 *
 */
public class Posts {

	private String url;

	private String charset;

	public Posts(String url) {
		this.url = url;
	}

	public boolean login(String userName, String password) throws Exception {
		// 首先获取网站的编码
		Document doc = Jsoup.connect(url + "member.php?mod=logging&action=login").get();
		String content = doc.select("[http-equiv^=Content-Type]").first().attr("content");
		String charset = content.substring(content.indexOf("=") + 1);
		System.out.println("网站编码为：" + charset);

		this.charset = charset;
		// 获取登陆链接
		Element formEle = doc.select("form").select("[name^=login]").first();
		String action = formEle.attr("action");
		// 构造登陆参数
		Map<String, String> paramters = new HashMap<>();
		// 得到所有表单的数据
		Elements inputEle = formEle.select("input");
		for (Element element : inputEle) {
			paramters.put(element.attr("name"), element.attr("value"));
		}
		// 设置用户名密码
		paramters.put("username", userName);
		paramters.put("password", password);
		// 登陆
		CloseableHttpResponse respone = HttpClient.httpPost(url + action, paramters, charset);
		String loginRes = EntityUtils.toString(respone.getEntity());
		String vwmyCLass = Jsoup.parse(loginRes).select(".vwmy").text();

		if (null != vwmyCLass && !vwmyCLass.equals("")) {
			System.out.println("登陆成功：" + vwmyCLass);
			return true;
		}
		System.out.println("登陆失败！！！");
		return false;
	}

	public boolean posts(PostBean postbean) throws ParseException, IOException, Exception {
		// 访问发帖页面，构造发帖参数
		Document Postdoc = Jsoup
				.parse(EntityUtils.toString(HttpClient.httpGet(postbean.getUrl(), postbean.getUrl()).getEntity()));

		Elements formEle = Postdoc.select("#postform");
		String urlpost = url + formEle.attr("action");
		// 构造参数
		Map<String, String> paramters = new HashMap<>();
		paramters.put("formhash", formEle.select("[name^=formhash]").val());
		paramters.put("posttime", formEle.select("[name^=posttime]").val());
		Elements secqaaEle = formEle.select("[id^=secqaa_]");
		// 验证码请求地址：http://bbs.zhuji.net/misc.php?mod=secqaa&action=update&idhash=Sde2ehe0&inajax=1&ajaxtarget=s
		// 查看是否需要验证码，如果是secqaa这是这种验证简单的：类似5-3=？这种
		if (null != secqaaEle && !secqaaEle.equals("")) {
			// 验证码验证
			System.out.println(secqaaEle);
			String secqaa = secqaaEle.attr("id");
			String secqaaid = secqaa.substring(secqaa.indexOf("_") + 1);
			// 生成验证码
			// 请求头需要增加referer,不然会拒绝请求
			String sss = EntityUtils
					.toString(
							HttpClient
									.httpGet(url + "misc.php?mod=secqaa&action=update&idhash=" + secqaaid
											+ "&inajax=1&ajaxtarget=secqaa_" + secqaaid, postbean.getUrl())
									.getEntity());
			int begin = sss.indexOf("/>") + 2;
			int end = sss.indexOf(" = ?]");
			String sub = sss.substring(begin, end);
			String secanswer = "";
			if (sub.contains("-")) {
				int i = Integer.parseInt(sub.split("-")[0].trim()) - Integer.parseInt(sub.split("-")[1].trim());
				secanswer = String.valueOf(i);
			} else if (sub.contains("+")) {
				int i = Integer.parseInt(sub.split("\\+")[0].trim()) + Integer.parseInt(sub.split("\\+")[1].trim());
				secanswer = String.valueOf(i);
			}
			// 检查验证码是否正确
			// http://bbs.zhuji.net/misc.php?mod=secqaa&action=check&inajax=1&&idhash=SfKkK6k0&secverify=80
			Thread.sleep(2000);
			String secverify = EntityUtils.toString(HttpClient.httpGet(
					url + "misc.php?mod=secqaa&action=check&inajax=1&&idhash=" + secqaaid + "&secverify=" + secanswer,
					postbean.getUrl()).getEntity());
			System.out.println(secverify);
			// 设置请求信息
			paramters.put("secanswer", secanswer);
			paramters.put("sechash", secqaaid);
		}

		// 表单信息
		paramters.put("message", postbean.getMessage());
		if (null != postbean.getSubject()) {
			paramters.put("subject", postbean.getSubject());
		}

		String postHtml = EntityUtils.toString(HttpClient.httpPost(urlpost, paramters, charset).getEntity());
		Document parse = Jsoup.parse(postHtml);
		String text = parse.select("#messagetext>p").text();
		if (null != postHtml && postHtml.equals("") || !text.contains("抱歉")) {
			System.out.println("发帖成功:" + text);
			Thread.sleep(60 * 2 * 1000);
			return true;
		} else {
			System.out.println("失败！！！" + text);
			Thread.sleep(60 * 2 * 1000);
			return false;
		}

	}

}
